package cn.darkhorse.device.iot.parser;

import cn.darkhorse.device.iot.IParser;
import cn.darkhorse.device.iot.IotDataParseException;
import cn.darkhorse.device.iot.constant.IotConstant;
import cn.darkhorse.device.pojo.IotPointTable;
import cn.darkhorse.device.pojo.MqttData;
import cn.darkhorse.device.service.IotPointTableService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public abstract class BaseParser implements IParser {
    @Resource
    protected IotPointTableService iotPointTableService;

    @Resource
    protected RedisCache cache;

    @Override
    public Map<String, Object> parse(MqttData data) {
        return doParse(data, getGatewayDeviceId(data));
    }
    @Override
    public Map<String, Object> parse(MqttData data, Set<String> pointIds) {
        return doParse(data, getGatewayDeviceId(data),pointIds);
    }
    @Override
    public String getGatewayDeviceId(MqttData data) {
        if (StringUtils.isEmpty(data.getDeviceId())) {
            throw new IotDataParseException("设备id不能为空");
        }
        return data.getDeviceId();
    }

    /**
     * 解析参数
     * @param data
     * @return
     */
    abstract Map<String, Object> doParse(MqttData data, String gatewayDeviceId);

    /**
     * 解析参数 传入pointIds 优化速度
     * @param data
     * @param gatewayDeviceId
     * @param pointIds
     * @return
     */
    abstract Map<String, Object> doParse(MqttData data, String gatewayDeviceId,Set<String> pointIds);


    /**
     * 获取设备点位标识
     * @param gatewayDeviceId
     * @return Set<String>
     */
    protected Set<String> getPointIds(String gatewayDeviceId) {
        List<IotPointTable> pointTables = iotPointTableService.list(new LambdaQueryWrapper<IotPointTable>()
                .eq(IotPointTable::getGatewayDeviceId, gatewayDeviceId));

        return pointTables.stream().map(IotPointTable::getPointId).collect(Collectors.toSet());
    }

    /**
     * 将解析出来的实时数据添加到缓存
     * key = MqttData:real-data:gatewayDeviceId
     * @param gatewayDeviceId
     * @param pointValueMap
     */
    protected void addToCache(String gatewayDeviceId, Map<String, Object> pointValueMap) {
        cache.setCacheMap(IotConstant.CACHE_MQTT_DATA_REAL_DATA + gatewayDeviceId, pointValueMap);
    }
}
